<template>
  <div
    class="sidebar-box"
    :class="isHidden.value ? 'sidebar-hidden' : 'sidebar-show'"
  >
    <MenuBox :isHidden="isHidden" @toggle-sidebar="toggleSidebar" />
    <div class="sidebar" v-if="!isHidden.value">
      <div v-for="(group, date) in groupedChats" :key="date">
        <div class="date-label">{{ date }}</div>
        <div
          v-for="chat in group"
          :key="chat.chatId"
          @click="selectMenu(chat.chatId)"
          :class="{ active: activeMenu === chat.chatId }"
          class="sidebar-item"
        >
          <template v-if="activeMenu === chat.chatId && chat.editing">
            <input
              v-model="chat.title"
              class="edit-input"
              @blur="stopEditing(chat)"
              @keyup.enter="updateChatTitle(chat)"
            />
          </template>
          <template v-else>
            <span class="chat-title">{{ chat.title }}</span>
            <div class="action-icons" v-if="activeMenu === chat.chatId">
              <el-icon @click.stop="startEditing(chat)"><EditPen /></el-icon>
              <el-icon @click.stop="deleteChat(chat)"><Delete /></el-icon>
            </div>
          </template>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, watch, computed, onMounted, onBeforeUnmount } from "vue";
import { EditPen, Delete } from "@element-plus/icons-vue";
import MenuBox from "./MenuBox.vue";
import { updateChat, deleteChat as deleteChatApi } from "@/api/chat";
import { useChatStore } from "@/stores/chat";

export default {
  name: "Sidebar",
  components: {
    EditPen,
    Delete,
    MenuBox,
  },
  setup() {
    const chatStore = useChatStore();
    const isHidden = ref({ value: false });
    const activeMenu = ref(null);
    const projectId = ref(chatStore.projectId);

    // 关键修复1: 创建响应式引用用于强制更新
    const updateTrigger = ref(0);

    // 关键修复2: 监听新会话创建
    watch(
      () => chatStore.newlyCreatedChatId,
      (newChatId) => {
        if (newChatId) {
          activeMenu.value = newChatId;
          // 强制组件重新渲染
          updateTrigger.value++;
        }
      }
    );

    // 关键修复3: 使用计算属性获取会话列表并响应更新
    const chats = computed(() => {
      // 加入更新触发器确保响应式更新
      updateTrigger.value;
      return chatStore.chatList;
    });

    // 初始化时获取会话列表
    onMounted(() => {
      checkWindowSize();
      window.addEventListener("resize", checkWindowSize);
      fetchChats();
    });

    onBeforeUnmount(() => {
      window.removeEventListener("resize", checkWindowSize);
    });

    // 检查窗口大小（响应式）
    const checkWindowSize = () => {
      isHidden.value.value = window.innerWidth <= 768;
    };

    // 切换侧边栏显示/隐藏
    const toggleSidebar = () => {
      isHidden.value.value = !isHidden.value.value;
    };

    // 获取会话列表
    const fetchChats = async () => {
      try {
        await chatStore.fetchChatList();

        // 设置当前活动会话
        if (chats.value.length > 0) {
          // 优先选择新创建的会话
          if (
            chatStore.newlyCreatedChatId &&
            chats.value.some(
              (chat) => chat.chatId === chatStore.newlyCreatedChatId
            )
          ) {
            activeMenu.value = chatStore.newlyCreatedChatId;
            chatStore.chatId = chatStore.newlyCreatedChatId;
          }
          // 其次选择localStorage中保存的当前会话
          else if (
            localStorage.getItem("currentChatId") &&
            chats.value.some(
              (chat) => chat.chatId === localStorage.getItem("currentChatId")
            )
          ) {
            activeMenu.value = localStorage.getItem("currentChatId");
            chatStore.chatId = localStorage.getItem("currentChatId");
          }
          // 默认选择第一个会话
          else {
            activeMenu.value = chats.value[0].chatId;
            chatStore.chatId = chats.value[0].chatId;
          }
        }
      } catch (error) {
        console.error("获取会话列表失败:", error);
      }
    };

    // 按日期分组会话
    const groupedChats = computed(() => {
      const groups = {};
      chats.value.forEach((chat) => {
        const dateLabel = getDateLabel(chat.createTime);
        if (!groups[dateLabel]) {
          groups[dateLabel] = [];
        }
        groups[dateLabel].push(chat);
      });

      // 确保"今天"在最前面
      const sortedGroups = {};
      if (groups["今天"]) {
        sortedGroups["今天"] = groups["今天"];
      }
      Object.keys(groups)
        .filter((date) => date !== "今天")
        .forEach((date) => {
          sortedGroups[date] = groups[date];
        });

      return sortedGroups;
    });

    // 获取日期标签（今天、昨天、X天前）
    const getDateLabel = (createTime) => {
      const now = new Date();
      const chatDate = new Date(createTime);
      const diffInDays = Math.floor((now - chatDate) / (1000 * 3600 * 24));

      if (diffInDays === 0) {
        return "今天";
      } else if (diffInDays === 1) {
        return "昨天";
      } else {
        return `${diffInDays}天前`;
      }
    };

    // 选择会话菜单
    const selectMenu = async (chatId) => {
      activeMenu.value = chatId;
      chatStore.newlyCreatedChatId = null; // 清除新建标记
      await chatStore.selectChat(chatId);
    };

    // 开始编辑会话标题
    const startEditing = (chat) => {
      chat.editing = true;
    };

    // 停止编辑会话标题
    const stopEditing = (chat) => {
      chat.editing = false;
      updateChatTitle(chat);
    };

    // 更新会话标题
    const updateChatTitle = async (chat) => {
      try {
        await updateChat({
          projectId: projectId.value,
          chatId: chat.chatId,
          title: chat.title,
        });
        chat.editing = false;
      } catch (error) {
        console.error("更新会话标题失败:", error);
      }
    };

    // 删除会话
    const deleteChat = async (chat) => {
      try {
        await deleteChatApi(projectId.value, chat.chatId);
        chatStore.chatList = chatStore.chatList.filter(
          (c) => c.chatId !== chat.chatId
        );
        updateTrigger.value++;
        if (activeMenu.value === chat.chatId && chatStore.chatList.length > 0) {
          selectMenu(chatStore.chatList[0].chatId);
        }
      } catch (error) {
        console.error("删除会话失败:", error);
      }
    };

    return {
      isHidden,
      activeMenu,
      groupedChats,
      toggleSidebar,
      selectMenu,
      startEditing,
      stopEditing,
      updateChatTitle,
      deleteChat,
    };
  },
};
</script>

<style scoped>
.sidebar-box {
  height: 100vh;
  overflow-y: auto;
  background: #f8f9fa;
  box-shadow: 2px 0 5px rgba(0, 0, 0, 0.05);
  width: 320px !important;
  min-width: 320px !important;
}

.sidebar {
  padding: 0;
  margin: 20px 0;
}

.date-label {
  font-weight: bold;
  font-size: 14px;
  margin: 10px 0 5px 0;
  padding: 5px 20px;
  color: #666;
}

.sidebar-item {
  padding: 12px 25px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: space-between;
  transition: background-color 0.2s;
}

.sidebar-item:hover {
  background-color: #edf2ff;
}

.active {
  background-color: #e6f7ff;
  color: #1890ff;
}

.chat-title {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  padding-right: 10px;
  font-size: 15px;
}

.edit-input {
  flex: 1;
  margin-right: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 8px;
  font-size: 15px;
}

.action-icons {
  display: flex;
  align-items: center;
  gap: 12px;
}

.action-icons .el-icon {
  font-size: 16px;
  color: #999;
  transition: color 0.2s;
}

.action-icons .el-icon:hover {
  color: #1890ff;
}

@media (max-width: 1024px) {
  .sidebar-box {
    width: 280px !important;
    min-width: 280px !important;
  }
}

@media (max-width: 768px) {
  .sidebar-box {
    width: 240px !important;
    min-width: 240px !important;
  }

  .date-label {
    padding: 5px 15px;
  }

  .sidebar-item {
    padding: 10px 15px;
  }

  .chat-title,
  .edit-input {
    font-size: 14px;
  }
}
</style>